import {
  Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy, ViewChild, Renderer2,
  OnDestroy
} from '@angular/core';
import {ToolsService} from "@shared/service/tools/tools.service";
import {ActivatedRoute, Router} from "@angular/router";
import {SignUpService} from "@sign-up/sign-up.service";

import {ModalComponent} from "@shared/components/modal/modal.component";

import {Subject} from "rxjs/Subject";
import {DynamicFormDefault, MatchSignUpData, MatchSignupFieldsResp} from "@interface/index";
// import {DynamicFormDefault, MatchSignUpData} from "@interface/shared/shared.model";
// import {MatchSignupFieldsResp} from "@interface/match/match.model";

export class MemberIndex {
  matchIndex: number;
  memberIndex: number;
}

@Component({
  selector: 'sign-up-traditional-match',
  templateUrl: './sign-up-traditional-match.component.html',
  styleUrls: ['./sign-up-traditional-match.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class SignUpTraditionalMatchComponent implements OnInit, OnDestroy {
  public params = new MatchSignUpData();
  public addition: MatchSignupFieldsResp[];
  public contactDefault: DynamicFormDefault;
  public showModal: boolean;
  public signing = false;
  public contactArr: Array<DynamicFormDefault> = [];  // 请求参数时候是合并到一个数组里的
  public allArr: Array<Array<DynamicFormDefault>> = [];  // 页面显示用
  public typeArr: Array<string> = [];
  private chooseIndex: MemberIndex;
  private list: Array<any> = [];
  @ViewChild(ModalComponent) modal;
  private ngUnSubscribe: Subject<any> = new Subject<any>();
  private matchOrder: string;  // 赛事场次性别的字符串  1是男，2是女 eg: 1,11,12,22
  constructor(
          private toolsService: ToolsService,
          private route: ActivatedRoute,
          private signUpService: SignUpService,
          private router: Router,
          private renderer: Renderer2
  ) {
    this.route.queryParams.subscribe(param => {
      // this.params = {
      //   matchId: param['matchId'],
      //   orderNumber: param['orderNumber'],
      //   channelsId: param['channelsId'],
      //   groupType: param['goodsType'],
      //   matchOrder: param['matchOrder']  || '11'
      // };
      this.params.channelsId = param['channelsId'];
      this.params.matchId = param['matchId'];
      this.params.groupType = param['goodsType'];
      this.params.orderNumber = param['orderNumber'];
      this.matchOrder = param['matchOrder'] || '11';
      this.typeArr = this.matchOrder.split(',');
      this.typeArr.forEach(e => {
        const temp = [];
        for (let i = 0; i < e.length; i++) {
          temp.push(i);
        }
        this.list.push(temp);
        this.allArr.push([]);
      });
    });
  }

  ngOnInit() {
    this.getData();
    this.renderer.listen('window', 'popstate', this.popstateHandler.bind(this));
  }

  /**
   * 根据type 参数来获取 参赛类型
   * @returns {string}
   */
  getSignType(type) {
    return this.signUpService.getDoubleMatchSignType(type);
  }

  getBtnState() {
    let state = true;
    this.list.forEach((e, i) => {
      if (this.allArr[i].length !== e.length && state) {
        state = false;
      }
    });
    return state;
  }

  getData() {
    this.signUpService.getDynamicMatchInfo(this.params.matchId, this.params.orderNumber)
      .takeUntil(this.ngUnSubscribe)
      .subscribe(res => {
        if (res.result === '0') {
          if (res.data.matchSignupFields.length > 0) {
            this.addition = res.data.matchSignupFields;
          }
        }
      });
  }

  edit(indexObj) {
    this.manageIndexObj(indexObj);
    this.contactDefault = this.allArr[this.chooseIndex.matchIndex][this.chooseIndex.memberIndex];
  }

  add(indexObj) {
   this.manageIndexObj(indexObj);
  }

  manageIndexObj(indexObj) {
    this.chooseIndex = indexObj;
    this.modal.show();
    this.showModal = true;
  }

  saveForm(item) {
    const chooseIndex = this.chooseIndex;
    if (this.allArr[chooseIndex.matchIndex][chooseIndex.memberIndex]) {
      this.allArr[chooseIndex.matchIndex].splice(chooseIndex.memberIndex, 1, item);
    } else {
      this.allArr[chooseIndex.matchIndex].unshift(item);
    }
    this.reset();
  }

  reset() {
    this.chooseIndex = null;
    this.contactDefault = null;
    this.modal.hide();
    this.modal.goBack();
    this.showModal = false;
  }

  delCustomer() {
    this.allArr[this.chooseIndex.matchIndex].splice(this.chooseIndex.memberIndex, 1);
    this.reset();
  }

  sign() {
    if (this.signing) {
      return;
    }
    this.signing = true;
    const data = this.signUpService.getPerasonalSignData(this.params);
    this.contactArr = [];
    this.allArr.forEach((eachMatch, i) => {
      eachMatch.forEach(eachContact => {
        const contact = eachContact;
        contact['playNumber'] = i + 1;
        this.contactArr.push(contact);
      });
    });
    data['members'] = this.contactArr;
    this.toolsService.showLoading();
    this.signUpService
      .addMatchTeamSign(data)
      .subscribe((res) => {
        this.signing = false;
        this.toolsService.hideLoading();
        if (res['result'] === '0') {
          if (res.data.list.length > 0) {  // 如果已经创建了俱乐部
            this.router.navigate(['/sign-up/group/choose-club'], {queryParams: {orderNumber: this.params.orderNumber}});
          } else {
            this.router.navigate(['/sign-up/group/create-club'], {queryParams: {orderNumber: this.params.orderNumber}});
          }
        } else if (res.result === '9012') {
          this.toolsService.showToast('该商品已下架');
        } else if (res.result === '13002') {
          this.toolsService.showToast('提交失败，请查看订单状态是否正常');
        } else if (res.result === '9105') {
          const str = this.getSexErrMsg(res.data, this.allArr);
          const temp = {
            title: '参赛人员性别不符',
            message: str
          };
          this.toolsService.present(temp);
        } else if (res.result === '10013') {  // 用户已报名了;
          const str = this.signUpService.getHasSignMemberStr(res.data);
          const temp = {
            title: '用户已报名',
            message: str
          };
          this.toolsService.present(temp);
        } else if (res.result === '10012') {  // 年龄限制;
          const msgData = this.signUpService.getAgeLimitMsg(res.data);
          const temp = {
            title: `参赛人年龄不符 ${msgData.minAge} ~ ${msgData.maxAge} 岁`,
            message: `报名人: ${msgData.memberStr}`
          };
          this.toolsService.present(temp);
        } else {
          this.toolsService.showToast(res.msg);
        }
      });
  }

  /**
   * @description  请求报名接口返回的性别不符合的场次信息
   * @author ouxh
   * @date 2017-10-26
   * @param data: { data :[{playNumber: '', title:'' }] } 跟 年龄限制的数据结构一样，data里面包含data（类型可变，所以给了data字段）
   * @param typeArr :[''] //eg: ['1','22']
   * @return array
   */
  getSexErrMsg(data: any, allArr: Array<Array<DynamicFormDefault>>) {
    const str = [];
    data.data.forEach((e, i) => {
      const index = e.playNumber;
      str.push(e.title);
      allArr[index - 1].forEach(each => {
        str.push(`${each.commingName} ${each.sex === '1' ? '男' : '女'}`);
      });
    });
    return str;
  }

  // 返回时重置一次所有参数
  popstateHandler() {
    this.chooseIndex = null;
    this.contactDefault = null;
    this.showModal = false;
  }

  ngOnDestroy() {
    this.ngUnSubscribe.next();
    this.ngUnSubscribe.complete();
  }
}
